package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.LoMoAdapter;
import com.github.postsanf.yinian.bean.VoiceCardOrder;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.entity.YNUpTokenResponse;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

public class TimeGoodsLomoActivity extends BaseActivity implements View.OnClickListener {
    private ImageView timegood_back;
    private TextView tv_sure;
    private GridView gd_lomo;
    private UploadManager mUpManager;
    private String lomoUrl = null;
    private String url = null;
    private int count = 0;
    private List<String> list = new ArrayList<>();
    private ProgressDialog mProgressDialog;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (url == null) {
                        url = lomoUrl;
                    } else {
                        url = url + "," + lomoUrl;
                    }
                    count++;
                    mProgressDialog.setMessage(count + "-16张");
                    if (count == 16) {
                        goToOrder();
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_goods_lomo);
        mUpManager = application.getUploadManager();
        initView();
    }

    private void initView() {
        timegood_back = ((ImageView) findViewById(R.id.timegood_back));
        tv_sure = ((TextView) findViewById(R.id.tv_sure));
        gd_lomo = ((GridView) findViewById(R.id.gd_lomo));

        timegood_back.setOnClickListener(this);
        tv_sure.setOnClickListener(this);

        LoMoAdapter loMoAdapter = new LoMoAdapter(TimeGoodsLomoActivity.this, SelectedImg.bitmaplist);
        gd_lomo.setAdapter(loMoAdapter);
    }

    @Override
    protected void onRestart() {
        LoMoAdapter loMoAdapter = new LoMoAdapter(TimeGoodsLomoActivity.this, SelectedImg.bitmaplist);
        gd_lomo.setAdapter(loMoAdapter);
        super.onRestart();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.timegood_back:
                SelectedImg.bitmaplist.clear();
                SelectedImg.choosepic.clear();
                SharedPreferences sp = getSharedPreferences("ChoosePicActivity", MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("ChoosePicActivity", null);
                edit.putBoolean("isReplace", false);
                edit.commit();
                finish();
                break;
            case R.id.tv_sure:
                mProgressDialog = ProgressDialog.show(this, "上传进度", "0-16张");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < SelectedImg.bitmaplist.size(); i++) {
                            list.add(saveBitmap(SelectedImg.bitmaplist.get(i)));
                        }
                        getToken();
                        SelectedImg.bitmaplist.clear();
                    }
                }).start();
                break;
        }
    }

    public String saveBitmap(Bitmap bm) {
        File yinianfile = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!(yinianfile.mkdir() || yinianfile.isDirectory())) {
            yinianfile.mkdirs();
        }
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian/" + System.currentTimeMillis() + ".jpg");
        if (file.exists()) {
            file.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file.toString();
    }

    // 获取上传Token
    private void getToken() {
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            application.setUpToken(resToken.getData().get(0).getToken());
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    for (int i = 0; i < list.size(); i++) {
                                        getCoverPicAddress(list.get(i));
                                    }
                                }
                            }).start();

                        } else {
                            showToast(resToken.getMsg());
                            mProgressDialog.dismiss();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                        mProgressDialog.dismiss();
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 获取七牛云地址
    private void getCoverPicAddress(String path) {
        String imgName = UUID.randomUUID().toString();
        mUpManager.put(path, imgName, application.getUpToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        if (info.isOK()) {
                            lomoUrl = key;
                            Log.d("yuhao", "getCoverPicAddress");
                            handler.sendEmptyMessage(0);
                        } else {
                            mProgressDialog.dismiss();
                        }
                    }
                }, new UploadOptions(null, null, false, new UpProgressHandler() {
                    public void progress(String key, double percent) {

                    }
                }, null));
    }

    private void goToOrder() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_GOODS_ID, String.valueOf(MainActivity.goodsid));
        mParam.put(CommonConstants.PICTURE, url);
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/eb/AddItem")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        VoiceCardOrder voiceCardOrder = gson.fromJson(s, VoiceCardOrder.class);
                        if (TextUtils.equals(voiceCardOrder.getMsg(), "success")) {
                            Log.d("yuhao", "success");
                            String itemid = voiceCardOrder.getData().get(0).getItemID();
                            String couponPrice = voiceCardOrder.getData().get(0).getCouponPrice();
                            String postage = voiceCardOrder.getData().get(0).getPostage();
                            Intent intent = new Intent(TimeGoodsLomoActivity.this, OrderActivity.class);
                            intent.putExtra("couponPrice", couponPrice);
                            intent.putExtra("postage", postage);
                            intent.putExtra("itemid", itemid);
                            Log.d("yuhao", "itemid=" + itemid);
                            for (int i = 0; i < list.size(); i++) {
                                File file = new File(list.get(i));
                                if (file.exists()) {
                                    file.delete();
                                }
                            }
                            intent.putExtra("goodsid", MainActivity.goodsid);
                            startActivity(intent);
                            finish();
                        }
                        mProgressDialog.dismiss();
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                        mProgressDialog.dismiss();
                    }
                });
        liteHttp.executeAsync(req);
    }

    @Override
    public void onBackPressed() {
        SelectedImg.bitmaplist.clear();
        SelectedImg.choosepic.clear();
        SharedPreferences sp = getSharedPreferences("ChoosePicActivity", MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("ChoosePicActivity", null);
        edit.putBoolean("isReplace", false);
        edit.commit();
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
//        Log.d("yuhao", "onDestroyssss");
//        SharedPreferences sp = getSharedPreferences("ChoosePicActivity", MODE_PRIVATE);
//        SharedPreferences.Editor edit = sp.edit();
//        edit.putString("ChoosePicActivity",null);
//        edit.commit();
        SelectedImg.seleBitmap.clear();
        SelectedImg.mSelectedImage.clear();
//        SelectedImg.bitmaplist.clear();
        super.onDestroy();
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
